package com.example.myapplication

import android.Manifest
import android.annotation.SuppressLint
import android.app.ProgressDialog
import android.graphics.BitmapFactory
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.blankj.utilcode.util.PermissionUtils
import com.example.myapplication.util.BitmapUtils
import com.wakeup.sdk.ble.WeikeBleMgr
import com.wakeup.sdk.ble.ext.BaseCallback
import com.wakeup.sdk.ble.ext.EventType
import com.wakeup.sdk.ble.ext.OnEventListener
import com.wakeup.sdk.ble.ext.connect.DeviceState
import com.wakeup.sdk.ble.utils.DeviceInfoDao
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

/**
 * @Author:  zgh
 * @CreateDate:  2023/10/31 10:39
 * @Description: Aigc功能界面
 */
class AigcActivity : AppCompatActivity() {

    lateinit var contentTv: TextView
    private val TAG = AigcActivity::class.java.name

    private val callback = object : OnEventListener {
        override fun onEvent(type: EventType, code: Int, data: Any?) {
            Log.i(TAG, "type = $type ; code = $code ; data = $data")
            when (type) {
                EventType.TYPE_DEVICE_STATE -> {
                    if (code == DeviceState.STATE_CONNECT_FAIL || code == DeviceState.STATE_NO_CONNECTION) {
                        finish()
                    }
                }
                // 设备请求app是否在前台
                EventType.TYPE_IS_FOREGROUND -> {
                    //true: 前台  false：后台
                    WeikeBleMgr.sendIsForeground(true)
                }
                // 设备控制录音
                EventType.TYPE_RECORD_AUDIO -> {
                    // data: 0： 开始录音 1：结束录音,2：重新录制，3：取消录制
                    when (data as Int) {
                        0 -> Toast.makeText(this@AigcActivity, "开始录音", Toast.LENGTH_SHORT)
                            .show()

                        1 -> Toast.makeText(this@AigcActivity, "结束录音", Toast.LENGTH_SHORT)
                            .show()

                        2 -> Toast.makeText(this@AigcActivity, "重新录制", Toast.LENGTH_SHORT)
                            .show()

                        3 -> Toast.makeText(this@AigcActivity, "取消录制", Toast.LENGTH_SHORT)
                            .show()
                    }
                }
                // 设备请求AIGC相关
                EventType.TYPE_REQUEST_AIGC -> {
                    // code 0：请求当前样式  1：请求生成图片
                    when (code) {
                        0 -> {
                            WeikeBleMgr.sendAigcStyle("样式一")
                            Toast.makeText(this@AigcActivity, "请求当前样式", Toast.LENGTH_SHORT)
                                .show()
                        }

                        1 -> {
                            // data 0：开始生成 1：重新生成 2：取消生成
                            when (data as Int) {
                                0 -> Toast.makeText(
                                    this@AigcActivity,
                                    "开始生成图片",
                                    Toast.LENGTH_SHORT
                                ).show()

                                1 -> Toast.makeText(
                                    this@AigcActivity,
                                    "重新生成图片",
                                    Toast.LENGTH_SHORT
                                ).show()

                                2 -> Toast.makeText(
                                    this@AigcActivity,
                                    "取消生成图片",
                                    Toast.LENGTH_SHORT
                                ).show()
                            }
                        }
                    }
                }

                else -> {}
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_aigc)

        WeikeBleMgr.registerListener(
            callback,
            EventType.TYPE_DEVICE_STATE,   // 连接状态
            EventType.TYPE_IS_FOREGROUND,  // 设备请求app是否在前台
            EventType.TYPE_RECORD_AUDIO,       // 设备控制录音
            EventType.TYPE_REQUEST_AIGC        // 设备请求AIGC相关
        )
        val connectDevice = WeikeBleMgr.getConnectDevice()
        if (connectDevice != null) {
            findViewById<TextView>(R.id.deviceStateTv).text =
                "name: ${connectDevice.bleName} \nmac: ${(connectDevice.mac)}"
        }
        contentTv = findViewById(R.id.contentTv)
        contentTv.movementMethod = ScrollingMovementMethod.getInstance()

        // App是否在前台
        findViewById<View>(R.id.app_foreground).setOnClickListener {
            //true: 前台  false：后台
            WeikeBleMgr.sendIsForeground(true)
        }
        // 当前aigc样式
        findViewById<View>(R.id.aigc_style).setOnClickListener {
            WeikeBleMgr.sendAigcStyle("样式一")
        }
        // 图片生成结果
        findViewById<View>(R.id.create_status).setOnClickListener {
            //result 0失败 1成功
            WeikeBleMgr.sendAigcCreateState(1)
        }
        // 语音转换结果
        findViewById<View>(R.id.voice_result).setOnClickListener {
            // resultCode 0：失败 1：成功 2：无麦克风权限
            // runCode Int 0：过程包 1：结束包
            // result String 内容
            WeikeBleMgr.sendAigcSpeakText(1, 1, "语音转换结果")
        }
        // 安装ai表盘
        findViewById<View>(R.id.ai_dial).setOnClickListener {
            val mProgressDialog = ProgressDialog(this)
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
            mProgressDialog.setTitle("表盘推送中")
            mProgressDialog.setCancelable(false)
            PermissionUtils.permission(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            )
                .callback(object : PermissionUtils.SimpleCallback {
                    override fun onGranted() {
                        GlobalScope.launch(Dispatchers.IO) {
                            var bitmap = BitmapFactory.decodeResource(
                                this@AigcActivity.resources,
                                R.mipmap.img_album_def
                            )
                            val deviceInfoModel =
                                DeviceInfoDao.getDeviceInfoModel(WeikeBleMgr.getLastMac())
                            // 表盘类型 圆or方
                            val isRound = deviceInfoModel.screenType == 0
                            if (isRound) {
                                bitmap = BitmapUtils.getCircleBitmap(bitmap)
                            }
                            if (deviceInfoModel.resolution.size >= 2) {
                                val scaleBitmap =
                                    BitmapUtils.scale(
                                        bitmap,
                                        deviceInfoModel.resolution[0],
                                        deviceInfoModel.resolution[1]
                                    ) ?: return@launch
                                WeikeBleMgr.installAiDial(
                                    this@AigcActivity,
                                    WeikeBleMgr.getLastMac(),
                                    scaleBitmap,
                                    object : BaseCallback<Int>() {
                                        override fun callback(code: Int, t: Int) {
                                            Log.i(TAG, "aiDial push code = $code ; msg = $t")
                                            when (code) {
                                                0 -> mProgressDialog.show()
                                                1, 2 -> mProgressDialog.progress = t
                                                3, -1 -> mProgressDialog.dismiss()
                                            }
                                        }
                                    })
                            }
                        }
                    }

                    override fun onDenied() {

                    }

                }).request()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        WeikeBleMgr.unregisterListener(callback)
    }
}